package com.franklin.java.completion;

import com.franklin.java.utils.PsiUtils;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * @author Franklin
 * @since 2021/9/10 9:50
 */
public class MyInsertHandler implements InsertHandler<LookupElement> {
    @Override
    public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) {
        PsiFile psiFile = context.getFile();
        PsiElement fillElement = psiFile.findElementAt(context.getStartOffset());
        if (Objects.nonNull(fillElement)) {
            String fillElementText = fillElement.getText();
            String lookupString = item.getLookupString();
            int outOfLength = fillElementText.length() - lookupString.length();
            Document document = context.getDocument();
            if (outOfLength > 0) {
                int startOffset = PsiUtils.findStartOffsetInPsiFile(fillElement);
                document.replaceString(startOffset, startOffset + fillElementText.length(), lookupString);
                context.commitDocument();
            }
        }
    }
}
